<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2018/2/1 0001
 * Time: 11:40
 */
namespace App\Base\Exceptions;

use App\Base\Models\ResponseModel;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
       //return parent::render($request, $exception);
        $code = (empty($exception->getCode()) || !is_numeric($exception->getCode())) ? ApiException::DEFAULT_ERROR_CODE : $exception->getCode();

        $msg = config('app.debug')?$exception->getMessage():ApiException::DEFAULT_ERROR_MESSAGE;
        $data = null;
        if ($exception instanceof HttpResponseException) {
            $msg = $exception->getMessage();
        }elseif($exception instanceof NotFoundHttpException){
            $code = ApiException::ERROR_NOT_FOUND[0];
            $msg = ApiException::ERROR_NOT_FOUND[1];
        } elseif ($exception instanceof ModelNotFoundException) {
            $code = ApiException::ERROR_NOT_FOUND[0];
        } elseif ($exception instanceof AuthorizationException) {
            $code = ApiException::ERROR_AUTHORIZATION[0];
        } elseif ($exception instanceof ValidationException && $exception->getResponse()) {
            $code = ApiException::ERROR_VALIDATION[0];
            $data = $exception->getResponse()->getOriginalContent();
            $msg = ApiException::ERROR_VALIDATION[1];
        } elseif ($exception instanceof ApiException) {
            $code = $exception->getCode();
        }else if(empty($msg)){
            $msg=ApiException::DEFAULT_ERROR_MESSAGE;
        }

        $responseModel = new ResponseModel();
        $responseModel->setCode(0);
        $responseModel->setStatus($code);
           //判断如果为空先为系统异常
        $responseModel->setMsg($msg);
        $responseModel->setData($data);
        $responseModel->setIsError(true);

     $response = new Response($responseModel);
     $response->exception = $exception;
     return $response;
       //
    }
}
